<template>
  <div style="margin-top: 15px">
    <a-button type="primary" @click="visibleCategory=true">新增类别</a-button>
    <a-modal
        v-model:visible="visibleCategory"
        title="新增类别"
        ok-text="确定"
        cancel-text="取消"
        @ok="onOkCategory"
        v-loading="loading4"
    >
      输入类别 :<input v-model="addCategory" required>
    </a-modal>
  </div>
  <div style="background-color: white;">

    <a-table
        :columns="columns"
        :data-source="categoryList"
        class="components-table-demo-nested"
        :showHeader="false"
        :loading="loading"
        @expand="expand"
        size="small"
    >
      <template #bodyCell="{ column,record }">
        <template v-if="column.key === 'delete'">
          <div style="gap: 20px;display: flex">
            <div><a-button type="link" @click="modalLabel(record.category)"><plus-outlined />新标签</a-button></div>

            <div style="margin-top: 5px">
              <a-popconfirm
                  title="删除？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="deleteCategory(record.category)"
              >
                <delete-outlined style="color:red;"/>
              </a-popconfirm>

            </div>
          </div>
        </template>
      </template>
      <template #expandedRowRender="{record}">
        <a-table
            :columns="innerColumns"
            :data-source="innerData"
            :pagination="false"
            :showHeader="false"
            :loading="loading2"
            style="background-color:#f7f7f7;"
        >
          <template #bodyCell="{ column }">
            <template v-if="column.key === 'label'">
              <span>
                <a-tag
                    v-for="tag in labelList[record.key]"
                    :key="tag.label"
                    :color="tag.label === 'loser' ? 'volcano' : tag.label.length > 5 ? 'geekblue' : 'green'"

                >
                  {{ tag.label.toUpperCase() }} ({{tag.count}})
                  <a-popconfirm
                      title="确定删除此标签"
                      ok-text="是"
                      cancel-text="否"
                      @confirm="handleClose(tag.label,record.category)"
                  >
                    <close-outlined style="color: red"/>
                  </a-popconfirm>

                </a-tag>
              </span>
            </template>
          </template>
        </a-table>
      </template>
    </a-table>

    <a-modal
        v-model:visible="visibleLabel"
        title="添加新标签"
        ok-text="确定"
        cancel-text="取消"
        @ok="onOkLabel"
        v-loading="loading3"
    >
      <a-form>
        <a-space
            v-for="(item,index) in addLabel"
            :key="index"
            align="baseline">
          <a-form-item
              :name="index"

          >
            <a-input v-model:value="addLabel[index]" placeholder="输入新标签" />
          </a-form-item>
          <MinusCircleOutlined @click="removeLabel(item)" />
        </a-space>
        <a-form-item>
          <a-button type="dashed" @click="handleAddLabel">
            <PlusOutlined />
            添加新标签
          </a-button>
        </a-form-item>
      </a-form>

    </a-modal>
  </div>
</template>

<script setup>
import {onMounted, ref,inject} from "vue";
import { PlusOutlined,DeleteOutlined,MinusCircleOutlined,CloseOutlined } from '@ant-design/icons-vue';
import request from "@/utils/request";
import {message} from "ant-design-vue";

const iinject=inject('reload')
const visibleLabel = ref(false);
const visibleCategory = ref(false);
const loading=ref(false)
const loading2=ref(false)
const loading3=ref(false)
const loading4=ref(false)
const categoryList = ref([]);
const labelList=ref([])
const addCategory=ref()
const addLabel=ref([])
const currentCategory=ref()
const innerData=ref([
  {
    label:''
  }
])
const customStyle = 'background: #f7f7f7;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden'

onMounted(()=>{
  loading.value=true
  request.get("category/getlist").then(res=>{
    console.log(res)
    for (let item in res.data){
      categoryList.value.push({key:item,category:res.data[item]})
    }

    loading.value=false
  })
})


const expand=(expanded, record)=>{
  if (expanded){
    if (labelList.value[record.key]===undefined){
      loading2.value=true
      request.get("label/get/bycategory/"+record.category).then(res=>{
        console.log(res)
        labelList.value[record.key]=res.data;
        console.log(labelList.value[record.key])
        // innerData.value=labelList.value[record.key]
        // for (let item in innerData.value){
        //   innerData.value[item].key=item
        // }
        loading2.value=false
      })
    }

  }
}

const columns = [{
  title: 'Category',
  dataIndex: 'category',
  key: 'category',
},
  {
    title: 'Delete',
    dataIndex: 'delete',
    key: 'delete',
    width:'12vw'
  },
]
const innerColumns=[{
  title:'Label',
  dataIndex:'label',
  key:'label',
  // align:'center'
},
  // {
  //   title:'Count',
  //   dataIndex:'count',
  //   key:'count'
  // }
]

const deleteCategory = category => {
  return new Promise(resolve => {
    request.get("category/admin/delete/"+category).then(res=>{
      console.log(res)
      if (res.status!==200){
        message.error(res.message)
      }
      else{
        iinject()
        message.success("类别已删除")
      }
    })
  });

};

const onOkLabel = () => {
  console.log(addLabel.value)
  loading3.value=true
  let reqLabel={category:currentCategory.value,labelSet:addLabel.value}
  console.log(reqLabel)
  request.post("label/admin/addSet",reqLabel).then(res=>{
    console.log(res)
    if (res.status!==200)
      message.error(res.message)
    else {
      message.success(res.message)
      addLabel.value=[]
      iinject()
      visibleLabel.value=false
    }
    loading3.value=false
  })
}

const modalLabel = (category) => {
  currentCategory.value=category
  visibleLabel.value=true
}

const removeLabel = item => {
  let indexAddLabel = addLabel.value.indexOf(item);

  if (indexAddLabel !== -1) {
    addLabel.value.splice(indexAddLabel, 1);
  }
  console.log(addLabel.value)
};

const handleAddLabel = () => {

  if (addLabel.value[addLabel.value.length-1]==='')
    message.warning("新标签不能为空")
  else if (isRepeat())
    message.warning("标签重复")
  else
    addLabel.value.push('')
  console.log(addLabel.value)
};

function isRepeat(){
  if (addLabel.value.length!==0){
    for (let x=0;x<addLabel.value.length-1;x++){
      if (addLabel.value[addLabel.value.length-1]===addLabel.value[x]){
        return true
      }
    }
    return addLabel.value[0] === '';

  }
}

const handleClose = (label,category) => {
  return new Promise(resolve => {
    request.post("label/admin/delete",{label:label,category:category}).then(res=>{
      console.log(res)
      if (res.status!==200){
        message.error(res.message)
      }
      else{
        iinject()
        message.success("标签已删除")
      }
    })
  });
}

const onOkCategory = () => {
  loading4.value=true
  request.post("category/admin/add",{category:addCategory.value}).then(res=>{
    console.log(res)
    if(res.status!==200)
      message.error(res.message)
    else{
      iinject()
      message.success("类别添加成功")
    }
    loading4.value=false
  })
}
</script>
